﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Com.Seezt.Skins;
using Components;
using Controls;
using UI.Lib;
using UI.Lib.Factory;
using System.Collections;

namespace UI.StorageManagement
{
    public partial class FrmOrdSendMedit : UI.ParentForm.BaseMedit
    {
        private string status;
        private bool IsPrint = false;

        public FrmOrdSendMedit(string modulecode, string action, string text, string key)
            : base(modulecode, action)
        {
            InitializeComponent();

            this.Text = text;
            this.Key = key;

            //回写的方法
            this.SaveCallFuntion = "OrdSendManager$SaveData"; //保存的方法
            IsAfterSaveCloseWin = false;
            base.MaxStateFlag = true;
            this.allowDtlEmpty = false; //可能用户一次想把全部的记录删除
            if (!string.IsNullOrEmpty(this.Key))
            {
                LoadData();
                IsAfterSaveCloseWin = true;
            }
            if ("P" == action)
            {
                tspBtnAdd.Visible = false;
                tspBtnDel.Visible = false;
                this.saveDtlDataToServer = false;
            }
        }

        public FrmOrdSendMedit(string modulecode, string action, string text, string key, string _status)
            : this(modulecode, action, text, key)
        {
            status = _status;

            SetToolButton(); //设置工具栏按钮
        }

        private bool? _hasCanModifyDocnoRight = null;

        private bool HasCanModifyDocnoRight
        {
            get
            {
                if (_hasCanModifyDocnoRight == null)
                {
                    var hsWhere = new Hashtable();
                    hsWhere["modulecode"] = this.ModuleCode;
                    hsWhere["actioncode"] = "N"; //是否有修改发货单的权限
                    hsWhere["usercode"] = Context.User.Uesrcode;

                    //查询数据库是否拥有重新打印的权限
                    DataTable dt = CommonHelper.Entity.ExecFun("checkRight", hsWhere);

                    _hasCanModifyDocnoRight = (null != dt && 0 != dt.Rows.Count);
                }


                return _hasCanModifyDocnoRight != null && _hasCanModifyDocnoRight.Value;
            }
        }

        /// <summary>
        /// 设置工具栏按钮
        /// </summary>
        private void SetToolButton()
        {
            if ("P" == this.Action)
            {
                tspSave.Visible = false;
                tspTop.Items.Insert(0, CreateToolBtn("P", ("11" == status ? "重新打印" : "打印配货单"),
                    new EventHandler(BtnPreDoc_Click)));
            }

            else if ("O" == this.Action) //打印的时候，生成打印按钮和重新打印按钮
            {
                tspSave.Visible = false;

                Hashtable hsWhere = new Hashtable();
                hsWhere["modulecode"] = this.ModuleCode;
                hsWhere["actioncode"] = "R";
                hsWhere["usercode"] = Context.User.Uesrcode;

                //查询数据库是否拥有重新打印的权限
                DataTable dt = CommonHelper.Entity.ExecFun("checkRight", hsWhere);

                //2是已经打印，5是回单已经录入， 设计的什么狗屁系统，靠
                if (null != dt && 0 != dt.Rows.Count && (status == "2" || status == "5" || "4" == status)) //拥有重新打印的权限
                {
                    if ("4" == status)
                        IsPrint = true;

                    tspTop.Items.Insert(0, CreateToolBtn("R", "重新打印", new EventHandler(RePrint_Click)));
                }

                if ("3" == status) //打印过的就不能再打印了
                {
                    tspTop.Items.Insert(0, CreateToolBtn("O", "打印送货单", new EventHandler(PrintBtn_Click)));
                }
            }
        }

        /// <summary>
        /// 重新打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void RePrint_Click(object sender, EventArgs e)
        {
            PrintBtn_Click(null, e);
        }

        /// <summary>
        /// 打印配货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BtnPreDoc_Click(object sender, EventArgs e)
        {
            //当前订单表主键
            string listid = Validation.ToString(this.tbSummary.GetValue("listid"));
            FrmOrdPreDoc frm = new FrmOrdPreDoc();
            frm.AddParam("listid", listid); //添加参数
            frm.Show();

            if (status == "11") return;

            if (!IsPrint)
            {
                Hashtable hsWhere = new Hashtable();
                hsWhere["listid"] = listid;

                string errmsg = CommonHelper.Entity.SaveDtl(this.SaveCallFuntion, StringUtil.Entity.TableToJson(hsWhere), "X", null, null);
                bool isSuccess = string.IsNullOrEmpty(errmsg); // 是否保存成功
                if (!isSuccess) MessageBox.Show(errmsg, "提示");
                else
                {
                    saveSuccessCount++;
                    base.IsReloadAfterSave = true;
                }

                IsPrint = true;
            }
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void PrintBtn_Click(object sender, EventArgs e)
        {
            //string listid = Validation.ToString(this.tbSummary.GetValue("listid"));
            var frm = new FrmOrdSendPrint();
            frm.AddParam("listid", _lastSaveId); //添加参数
            frm.Show();

            if (sender != null) //设置订单状态为2（已打印）
            {
                if (!IsPrint && false) //stone 2013-05-29 由于多次发货，所以不便于更新此状态，所以屏蔽
                {
                    Hashtable hsWhere = new Hashtable();
                    hsWhere["listid"] = Validation.ToString(this.tbSummary.GetValue("listid"));

                    string errmsg = CommonHelper.Entity.SaveDtl(this.SaveCallFuntion,
                                                                StringUtil.Entity.TableToJson(hsWhere), "P", null, null);
                    bool isSuccess = string.IsNullOrEmpty(errmsg); // 是否保存成功
                    if (!isSuccess) MessageBox.Show(errmsg, "提示");
                    else
                    {
                        saveSuccessCount++;
                        base.IsReloadAfterSave = true;
                    }

                    IsPrint = true;
                }
            }
        }

        protected override void PageInit()
        {
            this.tbSummary.DefaultWidth = 100;

            //隐藏新增和删除明细按钮
            tspBtnAdd.Visible = false;
            tspBtnDel.Visible = false;
        }

        protected override void AfterSystemChangeControlState()
        {
            base.AfterSystemChangeControlState();

            if ("A" == this.Action)
            {
                var hasRight = HasCanModifyDocnoRight;
                if (!hasRight)
                {
                    this.tbSummary.Enable("sendocno", false);
                }

                //填入最后的发货单号
                else
                {
                    var docno = GetLastSendNo();
                    _ignoreSelldocno = true;
                    this.tbSummary.SetValue("sendocno", docno);
                    _ignoreSelldocno = false;
                }
            }
        }

        private bool _ignoreSelldocno = false;

        protected override bool BeforeDtlPopUp(string name, ref string where, ref string[] others)
        {
            if ("productcode" == name)
            {
                where = Context.GetAppKeyWhere("a.muser");
            }

            return true;
        }

        protected override void AfterCreateSummaryControl(string name, Control c)
        {
            if ("sendocno" == name) //验证销售单号是否存在
            {
                var txtSellDocno = c as TextBoxX;
                if (txtSellDocno != null)
                    txtSellDocno.ValueChanged += TxtSellDocnoValueChanged;
            }
        }

        private void TxtSellDocnoValueChanged(object sender, EventArgs e)
        {
            //连接数据库，验证存在性
            if (("A" == this.Action || "M" == this.Action) && this.isLoadOk && !_ignoreSelldocno)
            {
                string sendocno = Validation.ToString(this.tbSummary.GetValue("sendocno"));
                if (string.IsNullOrEmpty(sendocno)) return;

                var hs = new Hashtable();
                hs["listid"] = this.tbSummary.GetValue("listid");
                hs["muser"] = Context.Comocde;
                hs["docno"] = sendocno;
                string reflt = CommonHelper.Entity.ExecFunScalar("checksenddocno", hs);
                if (!string.IsNullOrEmpty(reflt))
                {
                    MessageBox.Show("当前输入的发货单号重复，请重新录入！", "提示");
                    if (null == sender) this.tbSummary.ClearItem("sendocno");
                    else ((TextBoxX)sender).Revocation(); //重置
                }
            }
        }

        //加载修改数据
        private void LoadData()
        {
            base.LoadEditData(null, string.Format(" a.listid ='{0}' ", this.Key));
            base.LoadDtlData(null, string.Format(" a.plistid ='{0}' ", this.Key));

            if ("A" == this.Action)
            {
                this.dgvDtl.Focus(0, "dtlqty");  // 默认第一行的配送数量选中
                SetDefaultValue(); //设置默认值
            }
            else if ("B" == this.Action)
            {
                this.dgvDtl.Focus(0, "accqty");  // 默认第一行的配送数量选中
                SetDefaultValue(); //设置默认值
                this.tbSummary.SetValue("accamt", CalcDtlAmt());
            }

            var gainpct = Validation.ToDouble(this.tbSummary.GetValue("gainpct"));
            this.tbSummary.SetValue("gainpct", gainpct.ToString("0.00%")); //毛利率格式化
        }

        protected override void AfterSaveData(bool isSuccess)
        {
            if (isSuccess && "A" == this.Action)
            {
                //提示用户是否要打印
                if (MessageBox.Show("是否打印发货单？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //转跳到打印页面
                    PrintBtn_Click(tspBtnAdd, null);
                }
                else
                {
                    //Hashtable hsWhere = new Hashtable();
                    //hsWhere["listid"] = Validation.ToString(this.tbSummary.GetValue("listid"));

                    //string errmsg = CommonHelper.Entity.SaveDtl(this.SaveCallFuntion,
                    //                                            StringUtil.Entity.TableToJson(hsWhere), "U", null, null);
                    //isSuccess = string.IsNullOrEmpty(errmsg); // 是否保存成功
                    //if (!isSuccess) MessageBox.Show(errmsg, "提示");
                    //else
                    //{
                    //    saveSuccessCount++;
                    //    base.IsReloadAfterSave = true;
                    //}
                }
            }
        }

        private string _lastSaveId = string.Empty;
        protected override void AfterSaveSuccess(Dictionary<string, object> returnData)
        {
            _lastSaveId = string.Empty;

            if ("A" == this.Action)
            {
                if (returnData.ContainsKey("id"))
                    _lastSaveId = Validation.ToString(returnData["id"]);
            }
        }

        protected override void AfterReturnOfSave(ResultHelper result)
        {
            if ("A" == this.Action)
            {
                if (result.IsSuccess == false && result.ReturnObject != null)
                {
                    if (result.ReturnObject.ContainsKey("last") && HasCanModifyDocnoRight)
                    {
                        _ignoreSelldocno = true;
                        this.tbSummary.SetValue("sendocno", result.ReturnObject["last"]);
                        _ignoreSelldocno = false;
                    }
                }
            }
        }

        protected override bool Check()
        {
            if ("A" == this.Action) //保存时，验证配货数量 + 赠品数量必须小于或等于库存数量
            {
                var msg = new List<string>();
                foreach (DataGridViewRow dr in this.dgvDtl.Rows)
                {
                    if (Validation.ToDouble(dr.Cells["pqty"].Value)
                        + Validation.ToDouble(dr.Cells["dtlqty"].Value) > Validation.ToDouble(dr.Cells["ordqty"].Value))
                    {
                        msg.Add(string.Format("第{0}行【已发货数】+【本次发货量】大于了 【订货数量】\n", dr.Index + 1));
                    }
                }
                if (msg.Count > 0)
                {
                    if (MessageBox.Show(string.Join("", msg.ToArray()) + "\n是否确定继续操作？", "提示", MessageBoxButtons.YesNo) != System.Windows.Forms.DialogResult.Yes)
                    {
                        return false;
                    }
                }
            }
            else if ("B" == this.Action)
            {
                string backno = Validation.ToString(this.tbSummary.GetValue("backno"));
                if (string.IsNullOrEmpty(backno)) return true;

                Hashtable hs = new Hashtable();
                hs["backno"] = backno;
                hs["%muser"] = Context.GetAppKeyWhere();
                bool reflt = UI.Lib.Factory.CommonHelper.Entity.DataInData("Ord3a00", hs);
                if (reflt)
                {
                    MessageBox.Show("当前回单号码已经存在！", "提示");
                    this.tbSummary.Focus("backcno");
                    return false;
                }
            }

            return true;
        }

        private void SetDefaultValue()
        {
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                if ("A" == this.Action)
                {
                    //var sendQtyRemain = Validation.ToFloat(dr.Cells["ordqty"].Value) -
                    //                    Validation.ToFloat(dr.Cells["pqty"].Value);

                    //var preqtyRemain = Validation.ToFloat(dr.Cells["preqty"].Value) -
                    //                   Validation.ToFloat(dr.Cells["ppreqty"].Value);

                    var sendQty = 0;// Math.Max(sendQtyRemain, 0);

                    dr.Cells["dtlqty"].Value = sendQty; //发货时，配货数量默认等于订单数量
                    dr.Cells["actqty2"].Value = 0;// Math.Max(0, 0);

                    var cess = Validation.ToFloat(dr.Cells["cess"].Value);
                    var price = Validation.ToFloat(dr.Cells["ordprice"].Value);
                    var amt = sendQty * price;

                    dr.Cells["dtltotalamt"].Value = Math.Round(amt + amt * cess, 3);
                }
                else if ("B" == this.Action)
                {
                    dr.Cells["accqty"].Value = dr.Cells["pqty"].Value; //回单确认时，接受数量默认等于配货数量
                    dr.Cells["accpreqty"].Value = dr.Cells["ppreqty"].Value;

                    dr.Cells["accamt"].Value = Validation.ToDouble((Validation.ToDouble(dr.Cells["ordqty"].Value) *
                                Validation.ToDouble(dr.Cells["ordprice"].Value)), 3);
                }
            }
        }

        protected override void AfterDtlValueChanged(string name, object value)
        {
            if ("dtlqty" == name)
            {
                var sendQty = Validation.ToFloat(this.dgvDtl.GetValue("dtlqty"));
                var cess = Validation.ToFloat(this.dgvDtl.GetValue("cess"));
                var price = Validation.ToFloat(this.dgvDtl.GetValue("ordprice"));
                var amt = sendQty * price;

                this.dgvDtl.SetValue("dtltotalamt", Math.Round(amt + amt * cess, 3));
            }
            else if ("accqty" == name) //计算收货金额
            {
                double now = Validation.ToDouble(value);
                double ordprice = Validation.ToDouble(this.dgvDtl.GetValue("ordprice"));

                this.dgvDtl.SetValue("accamt", Validation.ToDouble(now * ordprice, 3));
            }
            else if ("accamt" == name)
            {
                this.tbSummary.SetValue("accamt", CalcDtlAmt());
            }
        }

        private double CalcDtlAmt()
        {
            double sum = 0;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                sum += Validation.ToDouble(dr.Cells["accamt"].Value);
            }

            return sum;
        }

        /// <summary>
        /// 获取最后单号
        /// </summary>
        /// <returns></returns>
        private string GetLastSendNo()
        {
            var hsWhere = QB.Entity.AddParam("muser", Context.User.Comcode);

            var dt = CommonHelper.Entity.ExecFun("getlastsendno", hsWhere);

            if (dt == null || 0 == dt.Rows.Count)
                return "";

            return Validation.ToString(dt.Rows[0][0]);
        }
    }
}
